
import { baseApi, shopApi } from '@/config'
import { aesEncrypt } from './AesUtil'
import { getSign } from './SignUtil'
import {
	router
} from '@/router/index.js';
import store from '@/store/index'
const miniProgramId = 'xxx'
const sysinfo = uni.getSystemInfoSync()
function disposeData(url, method, sendData) {
  let API = baseApi, urls = url
  // 如果是shop服务的,需要移除前置5个字符 所有shop服务的访问地址,都需要添加shop前缀,
  // 例如: 'shop/shop/mall/all/category' 因为需要判断当前服务,自动校正请求路径
  if (url.indexOf('shop') != -1) {
    API = shopApi
    urls = url.slice(5)
  }
  var timestamp = new Date().getTime()
  var token = uni.getStorageSync('token')
  var encryData = ''
  var datas = null
  if (
    method == 'post' &&
    !!sendData &&
    JSON.stringify(sendData) != '{}') {
    encryData = aesEncrypt(sendData)
    datas = { data: encryData }
  } else {
    datas = sendData
  }
  var sign = getSign(
    encryData,
    sysinfo.osName,
    '1.0.0',
    sysinfo.osName,
    timestamp
  )
  return new Promise((resolve, reject) => {
    uni.request({
      url: API + urls,
      method: method,
      data: datas,
      header: {
        'Content-Type': 'application/json',
        checkSign: 'true',
        checkToken: 'true',
        terminal: 5,
        platform: sysinfo.osName,
        version: '1.0.0',
        os: sysinfo.osName,
        appId: 'xxx',
        sign: sign,
        stamp: timestamp,
        channelParam: '',
        imei: '',
        channelCode: uni.getStorageSync('channelCode'),
        token: token,
        miniProgramId,
        deviceId: uni.getStorageSync('deviceId') || '',
        thirdPartyIdentify: sysinfo.deviceId
      },
      success: async({ data }) => {
        if (data.code !== 200) {
          if (data.code == 401 && url != '/aliMiniProgram/login' && uni.getStorageSync('user')) {
            router.push({ name: 'login', params: { isefficacy: true } })
          }
          resolve(data || 'error')
        } else {
          if (url != '/aliMiniProgram/login') {
            store.commit('steryBox/layout/resetRequestNum')
          }
          resolve(data)
        }
      },
      fail: (error) => {
        reject(error)
      }
    })
  })
}
/**
 * @description post方法
 * @returns Promise({})
 */
const post = (url, data = {}) => {
  return disposeData(url, 'post', data)
}
/**
 * @description get方法
 * @returns Promise({})
 */
const get = (url, data = {}) => disposeData(url, 'get', data)

//   403   token失效

export { post, get }
